﻿@namespace MudBlazor
@inherits MudComponentBase
@implements IAsyncDisposable

@if (Parent?.KeepPanelsAlive == true)
{
    <div @attributes="UserAttributes" class="@Class" style="display:@(Parent?.ActivePanel == this ? "contents" : "none");@Style">
        @ChildContent
    </div>
}
else
{
    @if (Parent?.ActivePanel == this)
    {
        @ChildContent
    }
}

@code {

    private Boolean _disposed;

    [CascadingParameter] private MudTabs Parent { get; set; }

    public ElementReference PanelRef;


    /// <summary>
    /// Text will be displayed in the TabPanel as TabTitle.
    /// </summary>
    [Parameter] public string Text { get; set; }

    /// <summary>
    /// Icon placed before the text if set.
    /// </summary>
    [Parameter] public string Icon { get; set; }

    /// <summary>
    /// If true, the tabpanel will be disabled.
    /// </summary>
    [Parameter] public bool Disabled { get; set; }

    /// <summary>
    /// Optional information to be showed into a badge
    /// </summary>
    [Parameter] public object BadgeData { get; set; }

    /// <summary>
    /// Optional information to show the badge as a dot.
    /// </summary>
    [Parameter] public bool BadgeDot { get; set; }

    /// <summary>
    /// The color of the badge.
    /// </summary>
    [Parameter] public Color BadgeColor { get; set; } = Color.Primary;

    /// <summary>
    /// Unique TabPanel ID. Useful for activation when Panels are dynamically generated.
    /// </summary>
    [Parameter] public object ID { get; set; }

    /// <summary>
    /// Raised when tab is clicked
    /// </summary>
    [Parameter] public EventCallback<MouseEventArgs> OnClick { get; set; }

    /// <summary>
    /// Child content of component.
    /// </summary>
    [Parameter] public RenderFragment ChildContent { get; set; }

    /// <summary>
    /// TabPanel Tooltip
    /// </summary>
    [Parameter] public string ToolTip { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if(firstRender == true && Parent != null)
        {
            await Parent.SetPanelRef(PanelRef);
        }
    }

    protected override void OnInitialized()
    {
        // NOTE: we must not throw here because we need the component to be able to live for the API docs to be able to infer default values
        //if (Parent == null)
        //    throw new ArgumentNullException(nameof(Parent), "TabPanel must exist within a Tabs component");
        base.OnInitialized();

        Parent?.AddPanel(this);
    }

    public async ValueTask DisposeAsync()
    {
        if(_disposed == true) { return;  }

        _disposed = true;
        await Parent?.RemovePanel(this);

    }
}
